package com.gitee.qdbp.base.orm.mybatis.converter;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

/**
 * EnumTypeHandler and EnumOrdinalTypeHandler not smart enough.<br>
 * when get result, if value is string then use enum.name() else use enum.ordinal().<br>
 * when set parameter, use PreparedStatement.setString(i, String.valueOf(parameter.ordinal()));<br>
 * -- if enum field jdbc type is varchar, will trigger a bug:<br>
 * -- WHERE varchar_field = 0; // it's wrong<br>
 * -- WHERE numeric_field = '0'; // no problem<br>
 * 
 * <pre>
 * EnumOrdinalHandler<E extends Enum<E>> extends EnumSmartHandler<E> {
 *     public EnumOrdinalHandler(Class<E> type) {
 *         super(type);
 *         this.useOrdinal = true; // force use ordinal
 *     }
 * }
 * EnumTolerantHandler<E extends Enum<E>> extends EnumSmartHandler<E> {
 *     public EnumTolerantHandler(Class<E> type) {
 *         super(type);
 *         this.withoutToDefault = true; // without value use null
 *     }
 * }
 * </pre>
 *
 * @author zhaohuihua
 * @see EnumOrdinalHandler
 * @see EnumTolerantHandler
 * @version 170524
 * @since V3.1.0
 */
public class EnumSmartHandler<E extends Enum<E>> extends BaseTypeHandler<E> {

    protected boolean useOrdinal = false;
    protected boolean withoutToDefault = false;
    protected Class<E> type;
    protected final E[] enums;

    public EnumSmartHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
        this.enums = type.getEnumConstants();
        if (this.enums == null) {
            throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        if (useOrdinal) {
            // WHERE numeric_field = '0'; // no problem
            // WHERE varchar_field =  0 ; // it's wrong
            ps.setString(i, String.valueOf(parameter.ordinal()));
        } else {
            ps.setString(i, parameter.name());
        }
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        if (rs.wasNull()) {
            return null;
        } else {
            return convertToEnum(value);
        }
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        if (rs.wasNull()) {
            return null;
        } else {
            return convertToEnum(value);
        }
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        if (cs.wasNull()) {
            return null;
        } else {
            return convertToEnum(value);
        }
    }

    protected boolean isDigit(String value) {
        if (value.length() == 0 || value.length() > 10) { // Integer.MAX_VALUE = 2147483647
            return false;
        }
        for (char c : value.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return true;
    }

    protected E convertToEnum(String value) {
        if (isDigit(value)) {
            int i = Integer.valueOf(value);
            if (i >= 0 && i <= enums.length - 1) {
                return enums[i];
            }
        } else {
            if (useOrdinal) {
                // force use ordinal, obviously cannot convert
            } else {
                for (E e : enums) {
                    if (e.name().equals(value)) {
                        return e;
                    }
                }
            }
        }

        if (withoutToDefault) {
            return getWithoutDefaultValue();
        } else {
            throw new IllegalArgumentException("Cannot convert " + value + " to " + type.getSimpleName() + ".");
        }
    }

    protected E getWithoutDefaultValue() {
        return null;
    }
}
